package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.dao.CouponDao;
import com.xiaobaibai.entity.Coupon;
import com.xiaobaibai.entity.CouponBelong;
import com.xiaobaibai.service.ICouponBelongService;
import com.xiaobaibai.service.ICouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-10-24
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponDao, Coupon> implements ICouponService {

    @Autowired
    private ICouponBelongService couponBelongService;

    @Override
    @Cacheable(value = "coupon",key = "#root.methodName")
    public List<Coupon> getCouponList() {
        QueryWrapper<Coupon> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","coupon_name","coupon_type","coupon_price","coupon_threshold","coupon_discount",
                "coupon_count","coupon_invalidation_time");
        //并且可领取张数要大于0
        queryWrapper.gt("coupon_remaining",0);
        queryWrapper.eq("coupon_status",true);
        return this.list(queryWrapper);
    }

    //领取优惠券
    @Override
    @Caching(evict = {
            @CacheEvict(value = "coupon",key = "'getUserHaveCoupon-'+#userId"),
            @CacheEvict(value = "coupon",key = "'getOkCouponList-'+#userId"),
            @CacheEvict(value = "coupon",key = "'getFailureCouponList-'+#userId"),
    })
    public boolean receiveCoupon(Integer userId, Integer couponId) {

        //1.先检验优惠券是否已经领取了此优惠券
        Set<Integer> userHaveCoupon = couponBelongService.getUserHaveCoupon(userId);
        if(userHaveCoupon.contains(couponId))
            return false;

        //2.再检查优惠券是否足够
        int i = this.baseMapper.receiveCoupon(couponId);
        if (i==0)
            return false;

        //可以领取了
        CouponBelong couponBelong=new CouponBelong();
        couponBelong.setCouponId(couponId);
        couponBelong.setStatus(0);//未使用
        couponBelong.setUserId(userId);
        couponBelongService.save(couponBelong);
        return true;
    }

}
